package com.ym.manager.admin.upload;

import com.ym.utils.Common;
import com.ym.utils.Logger;
import com.ym.utils.OssFileUtil;
import com.ym.utils.ResultUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * @program: ym_manager->UploadController
 * @Auther: 但何非
 * @Date: 2019/12/2 15:08
 * @Description: 上传
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    // 图片
    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(HttpServletRequest request, String uploadUrl){
        Map<String,Object> resMap = ResultUtil.result();
        Map<String,Object> data = new HashMap<String,Object>();
        try{
            // 获取文件
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = mreq.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, MultipartFile> entry = iter.next();
                MultipartFile file = entry.getValue();
                String ossPath;
                if(Common.isNotEmpty(uploadUrl)){
                    ossPath = "ddj/hos/"+ uploadUrl+System.currentTimeMillis()+"."+file.getOriginalFilename().split("\\.")[1];
                }else {
                    ossPath = "ddj/hos/"+ uploadUrl+System.currentTimeMillis()+"."+file.getOriginalFilename().split("\\.")[1];
                }
                OssFileUtil.putStream(ossPath,file.getInputStream());
                String url = OssFileUtil.DOMAIN + ossPath ;
                //上传图片返回url保存到数据库
                System.err.println(url);
                resMap.put("data",url);
                resMap.put("msg","上传成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            Logger.error(e);
            resMap.put("code",-1000);
            resMap.put("msg","上传失败");
        }
        return ResultUtil.toJSON(resMap);
    }

    //  富文本图片
    @RequestMapping("/uploadFileLayui")
    @ResponseBody
    public String uploadFileLayui(HttpServletRequest request){
        Map<String,Object> resMap = ResultUtil.result();
        Map<String,Object> data = new HashMap<String,Object>();
        try{
            // 获取文件
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = mreq.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> iter = map.entrySet().iterator();
            String result = null;
            while (iter.hasNext()) {
                Map.Entry<String, MultipartFile> entry = iter.next();
                MultipartFile file = entry.getValue();
//                result = FileUtil.putStream("wechat/dkNew/upload/backstage/layui/" + UUID.randomUUID().toString()
//                        + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), file.getInputStream());
                data.put("name",file.getOriginalFilename());
                data.put("src",result);
            }
            resMap.put("code",0);
            resMap.put("msg","上传成功");
            resMap.put("data",data);
        }catch (Exception e){
            e.printStackTrace();
            Logger.error(e);
            resMap.put("code",-1000);
            resMap.put("msg","上传失败");
        }
        return ResultUtil.toJSON(resMap);
    }


    // 图片
    @RequestMapping("/uploadImgData")
    @ResponseBody
    public String uploadImgData(HttpServletRequest request){
        Map<String,Object> resMap = ResultUtil.result();
        Map<String,Object> data = new HashMap<String,Object>();
        try{
            // 获取文件
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = mreq.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> iter = map.entrySet().iterator();
            String result = null;
            while (iter.hasNext()) {
                Map.Entry<String, MultipartFile> entry = iter.next();
                MultipartFile file = entry.getValue();
//                result = FileUtil.putStream("wechat/dkNew/upload/backstage/baiduImg/" + UUID.randomUUID().toString()
//                        + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), file.getInputStream());
                data.put("name",file.getOriginalFilename());
                data.put("url",result);
            }
            resMap.put("status",0);
            resMap.put("message","success");
            resMap.put("url",data.get("url"));
        }catch (Exception e){
            e.printStackTrace();
            Logger.error(e);
            resMap.put("status",-1000);
            resMap.put("message","");
        }
        return ResultUtil.toJSON(resMap);
    }

    // 视频
    @RequestMapping("/uploadVideoData")
    @ResponseBody
    public String uploadVideoData(HttpServletRequest request){
        Map<String,Object> resMap = ResultUtil.result();
        Map<String,Object> data = new HashMap<String,Object>();
        try{
            // 获取文件
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = mreq.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> iter = map.entrySet().iterator();
            String result = null;
            while (iter.hasNext()) {
                Map.Entry<String, MultipartFile> entry = iter.next();
                MultipartFile file = entry.getValue();
//                result = FileUtil.putStream("wechat/dkNew/upload/backstage/baiduVideo" + UUID.randomUUID().toString()
//                        + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), file.getInputStream());
                data.put("name",file.getOriginalFilename());
                data.put("url",result);
            }
            resMap.put("status",0);
            resMap.put("message","success");
            resMap.put("url",data.get("url"));
        }catch (Exception e){
            e.printStackTrace();
            Logger.error(e);
            resMap.put("status",-1000);
            resMap.put("message","");
        }
        return ResultUtil.toJSON(resMap);
    }


    // 文件
    @RequestMapping("/uploadData")
    @ResponseBody
    public String uploadData(HttpServletRequest request){
        Map<String,Object> resMap = ResultUtil.result();
        Map<String,Object> data = new HashMap<String,Object>();
        try{
            // 获取文件
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = mreq.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> iter = map.entrySet().iterator();
            String result = null;
            while (iter.hasNext()) {
                Map.Entry<String, MultipartFile> entry = iter.next();
                MultipartFile file = entry.getValue();
//                result = FileUtil.putStream("wechat/dkNew/upload/backstage/baiduFile" + UUID.randomUUID().toString()
//                        + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), file.getInputStream());
                data.put("name",file.getOriginalFilename());
                data.put("url",result);
            }
            resMap.put("status",0);
            resMap.put("message","success");
            resMap.put("url",data.get("url"));
        }catch (Exception e){
            e.printStackTrace();
            Logger.error(e);
            resMap.put("status",-1000);
            resMap.put("message","");
        }
        return ResultUtil.toJSON(resMap);
    }

    @RequestMapping("upload")
    @ResponseBody
    public String upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        Map<String, Object> result = ResultUtil.result();
//        System.out.println("执行upload");
        if(!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
//            System.out.println("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                if ("PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
//                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    String trueFileName = UUID.randomUUID()+""+System.currentTimeMillis() + "."+type;
                    // 设置存放图片文件的路径
//                    path = realPath + "images\\uploads\\" + trueFileName;
                    //现网
                    String base_path ="/opt/static/goods/promote/uploads/";
                    //本地
//                    String base_path = "D:\\java\\pic\\duoke_imgs\\images\\uploads\\";

                    path = base_path + trueFileName;

//                    System.out.println("存放图片文件的路径:" + path);
                    result = ThumbnalitorUtil.uploadFileAndCreateThumbnail(file,request,base_path);
                }else {
                    result.put("msg","不是我们想要的文件类型,请按要求重新上传");
                }
            }else {
                result.put("msg","文件类型为空");
            }
        }else {
            result.put("msg","没有找到相对应的文件");
        }
        return ResultUtil.toJSON(result);
    }
    @RequestMapping("upload/app")
    @ResponseBody
    public String uploadApp(HttpServletRequest request,String appName) throws IOException {
        Map<String, Object> result = ResultUtil.result();
        try{
            // 获取文件
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> map = mreq.getFileMap();
            Iterator<Map.Entry<String, MultipartFile>> iter = map.entrySet().iterator();
            MultipartFile file = null;
            while (iter.hasNext()) {
                Map.Entry<String, MultipartFile> entry = iter.next();
                file = entry.getValue();
            }
            if(!file.isEmpty()) {
                //现网
                String base_path ="/opt/static/sys/gw/apk/";
                result = ThumbnalitorUtil.uploadFileApp(appName,file,request,base_path);
            }else {
                result.put("msg","没有找到相对应的文件");
            }
        }catch (Exception e){
            e.printStackTrace();
            Logger.error(e);
            result.put("code",-1000);
            result.put("msg","上传失败");
        }

        return ResultUtil.toJSON(result);
    }
    /**
     * 遍历压缩图片
     * @return
     */
    @RequestMapping("ThumbnalitorPic")
    @ResponseBody
    public String ThumbnalitorPic()  {
        try {
//            ThumbnalitorUtil.isDirectory(new File("D:\\java\\pic\\duoke_imgs\\images\\uploads\\"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
}
